import React, { Component } from 'react';
import {
  Button,
  Cascader,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  message,
  Popconfirm,
  Row,
  Select,
  Upload,
} from 'antd';
import { defDrawerWidth } from '@/defaultSettings';
import styled from 'styled-components';
import { DivFooter, LFlexHDiv } from '@/components/MHtmlTag';
import styles from './index.less';
import { formatMessage } from 'umi-plugin-react/locale';
import BaseComponent from '@/components/BaseComponent';
import moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;

const InputDiv = styled.div`
  display: flex;
  width: 100%;
`;

const MLabel = styled.div`
  height: 40px;
  width: 150px;
  display: flex;
  align-items: center;
  padding-left: 8px;
  justify-content: flex-end;
  padding-right: 8px;
`;

const RequiredSpan = styled.span`
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
`;

const LabelSpan = styled.span`
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
`;

const PreviewImage = styled.img`
  width: 100%;
`;

/**
 * 输入组件
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const MFormInputItem = props => {
  const { fieldName = '', label = '', required = false, form, children, initialValue } = props;
  const { getFieldDecorator } = form;
  return (
    <InputDiv>
      <MLabel>
        {required ? <RequiredSpan>*</RequiredSpan> : null}
        <LabelSpan>{label}:</LabelSpan>
      </MLabel>
      <Form.Item style={{ flex: '1' }}>
        {children
          ? fieldName != ''
            ? getFieldDecorator(fieldName, {
                rules: [{ required: required, message: label != '' ? `请输入${label}` : '' }],
                initialValue: initialValue,
              })(children)
            : children
          : null}
      </Form.Item>
    </InputDiv>
  );
};

/**
 * 编辑企业信息
 */
@Form.create()
class EditView extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 是否正在上传图片
      uploadLoading: false,
      // 上传后的文件地址
      fileUrl: '',
    };
  }

  /**
   * 设置经纬度
   * @param lng
   * @param lat
   */
  setLngLat = ({ lng, lat }) => {
    const { form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      longitude: lng,
      latitude: lat,
    });
  };

  /**
   * 设置行业代码
   * @param code
   */
  setBusinessCode = ({ code }) => {
    const { form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      industry_involved: code,
    });
  };

  componentDidMount() {
    const { record, form } = this.props;
    const { business_license } = record;
    if (business_license && business_license != '') {
      this.setState({
        fileUrl: business_license,
      });
      // const { setFieldsValue } = form;
      // setFieldsValue({
      //   business_license: business_license,
      // });
    }
  }

  render() {
    const { onClose, visible = false, form, areaOptions = [], record } = this.props;
    return (
      <Drawer
        title="新增企业信息"
        placement="right"
        width={defDrawerWidth}
        closable={true}
        onClose={e => {
          if (onClose) {
            onClose(e);
          }
        }}
        visible={visible}
      >
        <div className={styles.mForm}>
          <Form>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'公司名称'}
                  fieldName={'company_name'}
                  required={true}
                  initialValue={record['company_name']}
                >
                  <Input placeholder={'请输入公司名称'} />
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'统一社会信用代码'}
                  fieldName={'social_code'}
                  required={true}
                  initialValue={record['social_code']}
                >
                  <Input placeholder={'统一社会信用代码'} />
                </MFormInputItem>
              </Col>
              <Col span={2}></Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'注册地址'}
                  fieldName={'company_address'}
                  initialValue={record['company_address']}
                  required={true}
                >
                  <Input placeholder={'请输入注册地址'} />
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'法人代表'}
                  fieldName={'legal_person'}
                  initialValue={record['legal_person']}
                  required={true}
                >
                  <Input placeholder={'请输入法人代表'} />
                </MFormInputItem>
              </Col>
              <Col span={2}></Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'成立日期'}
                  fieldName={'establishment_date'}
                  initialValue={moment(record['establishment_date'], 'YYYY-MM-DD')}
                  required={true}
                >
                  <DatePicker placeholder={'请输入成立日期'} style={{ width: '100%' }} />
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'营业期限'}
                  fieldName={'business_term'}
                  initialValue={moment(record['business_term'], 'YYYY-MM-DD')}
                  required={true}
                >
                  <DatePicker placeholder={'请输入营业期限'} style={{ width: '100%' }} />
                </MFormInputItem>
              </Col>
              <Col span={2}></Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'联系人'}
                  initialValue={record['contacts']}
                  fieldName={'contacts'}
                  required={true}
                >
                  <Input placeholder={'请输入联系人'} />
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'联系电话'}
                  initialValue={record['contacts_mobile']}
                  fieldName={'contacts_mobile'}
                  required={true}
                >
                  <Input placeholder={'请输入联系电话'} />
                </MFormInputItem>
              </Col>
              <Col span={2}></Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'单位类型'}
                  fieldName={'company_type'}
                  initialValue={`${record['company_type']}`}
                  required={true}
                >
                  <Select placeholder={'请选择单位类型'} style={{ width: '100%' }} allowClear>
                    <Option value="1">固体废物产生源单位</Option>
                    <Option value="2">危险废物运输单位</Option>
                    <Option value="3">经营单位</Option>
                  </Select>
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'所属行业'}
                  fieldName={'industry_involved'}
                  initialValue={record['industry_involved']}
                  required={true}
                >
                  <Input placeholder={'请选择所属行业'} />
                </MFormInputItem>
              </Col>
              <Col span={2}>
                <Button
                  style={{ marginTop: '4px', marginLeft: '8px' }}
                  type="primary"
                  onClick={this.handleSelectBusinessCodeClick}
                >
                  选择
                </Button>
              </Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'经度'}
                  initialValue={record['longitude']}
                  fieldName={'longitude'}
                  required={true}
                >
                  <Input placeholder={''} />
                </MFormInputItem>
              </Col>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'纬度'}
                  initialValue={record['latitude']}
                  fieldName={'latitude'}
                  required={true}
                >
                  <Input placeholder={''} />
                </MFormInputItem>
              </Col>
              <Col span={2}>
                <Button
                  onClick={this.handleSelectLocationClick}
                  style={{ marginTop: '4px', marginLeft: '8px' }}
                  type="primary"
                >
                  选择
                </Button>
              </Col>
            </Row>
            <Row>
              <Col span={22}>
                <MFormInputItem
                  form={form}
                  label={'所属地区'}
                  fieldName={'area_code'}
                  initialValue={record['area_code'].split('|')}
                  required={false}
                >
                  <Cascader options={areaOptions} />
                </MFormInputItem>
              </Col>
            </Row>
            <Row>
              <Col span={11}>
                <MFormInputItem
                  form={form}
                  label={'营业执照'}
                  fieldName={'business_license'}
                  initialValue={record['business_license']}
                  required={true}
                >
                  <div>
                    <Input style={{ display: 'none' }} />
                    <Upload
                      disabled={this.state.uploadLoading}
                      showUploadList={false}
                      action="/api/swservice/v1/sw/uploadFile"
                      onChange={this.handleUploadChange}
                    >
                      <Button loading={this.state.uploadLoading}>选择文件</Button>
                    </Upload>
                  </div>
                </MFormInputItem>
              </Col>
            </Row>
            {this.state.fileUrl != '' ? (
              <Row>
                <Col span={22}>
                  <MFormInputItem form={form} label={'预览'} required={false}>
                    <PreviewImage src={this.state.fileUrl} />
                  </MFormInputItem>
                </Col>
              </Row>
            ) : null}

            <Row>
              <Col span={22}>
                <MFormInputItem
                  form={form}
                  label={'经营范围'}
                  fieldName={'business_scope'}
                  initialValue={record['business_scope']}
                  required={false}
                >
                  <TextArea rows={4} style={{ width: '100%' }} />
                </MFormInputItem>
              </Col>
            </Row>
          </Form>
        </div>

        <DivFooter>
          <LFlexHDiv>
            <LFlexHDiv flex={'1'} justifyContent={'center'}>
              <Button
                style={{
                  marginRight: 8,
                  width: '120px',
                }}
                onClick={() => {
                  if (onClose) {
                    onClose();
                  }
                }}
              >
                取消
              </Button>
              <Popconfirm
                title="确定执行当前操作吗?"
                onConfirm={() => {
                  this.handleSubmit();
                }}
              >
                <Button type="primary" style={{ width: '120px' }}>
                  编辑
                </Button>
              </Popconfirm>
            </LFlexHDiv>
          </LFlexHDiv>
        </DivFooter>
      </Drawer>
    );
  }

  /**
   * 处理提交操作
   * @param e
   */
  handleSubmit = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { onConfirmClick, record } = this.props;
        if (onConfirmClick) {
          // 此处将数据进行一次转换
          const { area_code, business_term, establishment_date } = values;
          values['area_code'] = area_code.join('|');
          values['establishment_date'] = establishment_date.format('YYYY-MM-DD');
          values['business_term'] = business_term.format('YYYY-MM-DD');
          values['id'] = record['id'];
          onConfirmClick({ data: values });
        }
      } else {
        console.error('请将信息填写完整');
      }
    });
  };

  /**
   * 选择位置按钮被点击
   */
  handleSelectLocationClick = () => {
    const { onSelectLocationClick } = this.props;
    if (onSelectLocationClick) {
      onSelectLocationClick();
    }
  };

  /**
   * 选择行业代码被点击
   */
  handleSelectBusinessCodeClick = () => {
    const { onSelectBusinessCodeClick } = this.props;
    if (onSelectBusinessCodeClick) {
      onSelectBusinessCodeClick();
    }
  };

  /**
   * 上传状态改变
   * @param info
   */
  handleUploadChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({
        uploadLoading: true,
      });
      return;
    }
    if (info.file.status === 'done') {
      message.success(formatMessage({ id: 'app.file.upload-success' }));
      const {
        response: {
          // 文件存放地址
          data: { url },
        },
      } = info.file;
      this.setState({ fileUrl: url });

      const { form } = this.props;
      const { setFieldsValue } = form;
      setFieldsValue({
        business_license: url,
      });
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
    this.setState({
      uploadLoading: false,
    });
  };
}

export default EditView;
